/*  VKLADA FOTOGRAFIE DO DIVU + LOADING po Uploadu
 *  src : cesta k souboru
*/
$.fn.insertPhoto = function(src) {
  var id = $(this);
  id.addClass('loading');
  var img = new Image();
  $(img).load(function () {
    $(this).css('display', 'none');
    id.removeClass('loading');
    id.append(this);
    $(this).fadeIn();
  }).error(function () {
    // nastala chyba
    }).attr('src', src);
}

var cyrillic = [
"ě", "š", "č", "ř", "ž", "ý", "á", "í", "é", "ů", "ä", "ô", "ü", "ÿ", "â", "ê", "ë", "ö", "ú",
"а", "б", "в", "г", "д", "е", "ж", "з", "и", "й", "к", "л", "м", "н", "о",
"п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ь", "ю", "я",
"А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О",
"П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ь", "Ю", "Я",
"Ї", "ї", "Є", "є", "Ы", "ы", "Ё", "ё"
];

var latin = [
"e", "s", "c", "r", "z", "y", "a", "i", "e", "u", "a", "o", "u", "y", "a", "e", "e", "o", "u",
"a", "b", "v", "g", "d", "e", "zh", "z", "i", "y", "k", "l", "m", "n", "o",
"p", "r", "s", "t", "u", "f", "h", "ts", "ch", "sh", "sht", "a", "y", "yu", "ya",
"A", "B", "B", "G", "D", "E", "Zh", "Z", "I", "Y", "K", "L", "M", "N", "O",
"P", "R", "S", "T", "U", "F", "H", "Ts", "Ch", "Sh", "Sht", "A", "Y", "Yu", "Ya",
"I", "i", "Ye", "ye", "I", "i", "Yo", "yo"
];

var string = '';

$.fn.friendurl = function(options){

  var defaults = {
    divider : '-',
    transliterate: false
  };

  var options = $.extend(defaults, options);

  return this.each(function(){

    $(this).keyup(function(){
      var url = $(this).val()
      .toLowerCase() // change everything to lowercase
      .replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces
      .replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
      .replace(/[^a-z\u0400-\u04FF0-9-ěščřžýáíéúůäôüÿâêëö]+/g, "") // remove all non-cyrillic, non-numeric characters except the hyphen
      .replace(/[-]+/g, "-") // replace multiple instances of the hyphen with a single instance
      .replace(/^-+|-+$/g, "") // trim leading and trailing hyphens
      .replace(/[-]+/g, options.divider)
      ;

      if (options.transliterate) {
        url = convert(url);
      }

      $('#' + options.id).val(url);
    });

  });

  function convert (text) {
    string = str_replace(cyrillic, latin, text);
    return string;
  }

  function str_replace (search, replace, subject, count) {

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
      this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
      if (s[i] === '') {
        continue;
      }
      for (j=0, fl=f.length; j < fl; j++) {
        temp = s[i]+'';
        repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
        s[i] = (temp).split(f[j]).join(repl);
        if (count && s[i] !== temp) {
          this.window[count] += (temp.length-s[i].length)/f[j].length;
        }
      }
    }
    return sa ? s : s[0];
  }

};


$(document).ready(function() {

  // stylovani selectu a jeho odeslani formulari po zmene
  $('select').selectmenu({style:'dropdown'});
  
  $('select#select-sort').change(function() {
    this.form.submit();
  });

  // scrollovani k topu stranky + zobrazi login panel
  $('a#login-footer').click(function() {
    $('div#panel-login').show();
    $('html, body').animate({
      scrollTop: 0
    }, 900);
  });

  // zavreni info panelu
  $('a#close-info-panel-top').click(function() {
    $('div#panel-info').slideUp();
  });

  // zavreni login panelu
  $('a#close-login-panel-top').click(function() {
    $('div#panel-login').slideUp();
  });
  
  // zobrazeni panelu nastroju pro kazdy prvek v admin sekci
  $('.content-right-item').hover(
    function () {
      $(this).find('.content-right-tools').show();
    },
    function () {
      $(this).find('.content-right-tools').hide();
    }
    );

  /*  Nastroj pro orez fotografii
   *  id : id fotografie
  */
  function initJcrop(id) {
    if(jcrop_api) {
      jcrop_api.destroy();
    }
    var jcrop_api;
    jcrop_api = $.Jcrop(id);
    jcrop_api.setOptions({
      aspectRatio: 210/180,
      minSize: [ 105, 90 ],
      allowSelect: true
    });
  }

  $('.cropbox').mouseover(function() {
    elementID = $(this).attr("id");
    initJcrop('#'+elementID);
  });


  /*  scrollovani pro nahledy
   *  nejnovejsi, nejpopularnejsi fotografie
   */
  $('a#thumb-newest-next').click(function() {
    $('div#thumb-newest ul').animate({
      left: '-=681'
    }, 800);
  });

  $('a#thumb-newest-prev').click(function() {
    $('div#thumb-newest ul').animate({
      left: '+=681'
    }, 800);
  });

  // Dalsi informace po :hover na nahled
  $('.thumb-hover ul li a').hover(
    function () {
      $(this).find('.thumb-info').fadeIn();
    },
    function () {
      $(this).find('.thumb-info').fadeOut();
    }
    );

  $('ul.thumbs li a').hover(
    function () {
      $(this).find('.thumb-edit').fadeIn();
    },
    function () {
      $(this).find('.thumb-edit').fadeOut();
    }
    );

  // Přidá ajaxem novou kategorii pro článek
  $('a#articles-cat-add').click(function() {
    var item = $('input[name=new_category]');
    $.post("/ajax/articles_cat_add/", {new_category: item.val()},
    function(data){
      if(data.check == 'ok') {
        item.before('<label><input type="checkbox" name="categories[]" value="'+data.id+'" class="text" />'+data.name);
        item.val('');
      } else {
        alert('Kategorie již existuje nebo došlo k chybě.');  
      }
    }, 'json');
  });

  // Vytvoří pole tagů pro článek
  var num = 1;
  $('a#articles-tag-add').click(function() {
    var item = $('input#tags');    
    if(item.val().length > 0) {
      $('div#container-tags').after('<label id="article-tag'+num+'" class="text-tags"><input type="hidden" readonly="readonly" name="article_tags[]" value="'+item.val()+'" />'+item.val()+' <a href="javascript:;" onclick="$(\'#article-tag'+num+'\').remove();" class="href-gray" title="Odstranit">(x)</a></label>');
      num++;
      item.val('');
    }
  });

  // Vytvoří pole tagů pro ostatní sekce
  var tagnum = 1;
  $('a#tag-add').click(function() {
    var item = $('input#tags');
    if(item.val().length > 0) {
      $('div#container-tags').after('<label id="tag'+tagnum+'" class="text-tags"><input type="hidden" readonly="readonly" name="tags[]" value="'+item.val()+'" />'+item.val()+' <a href="javascript:;" onclick="$(\'#tag'+tagnum+'\').remove();" class="href-gray" title="Odstranit">(x)</a></label>');
      tagnum++;
      item.val('');
    }
  });

  $('#title').friendurl({id : 'seo_title', transliterate: true});

  /* Plný náhled pro fotografie */
  $('img.full-photo-open').click(function() {
    $("body").addClass('full-photo');   
    $('#full-photo-canvas').fadeIn();
    $(window).resize();
    /* Aktivace klaves */
    $(document).bind('keydown',keyboardArrow);
  });

  $('a#full-photo-next').click(function() {
    righSlide();
  });

  $('a#full-photo-prev').click(function() {
    leftSlide();
  });

  $('#full-photo-close a').click(function() {
    $("body").removeClass('full-photo');
    $('#full-photo-canvas').fadeOut('slow');
  });

  $('#full-photo-change a').click(function() {
    if($(this).html() == 'Tmavé pozadí') {
      $('#full-photo-canvas').css('background','#181015 url("/media/img/container_dark.gif") repeat left top');
      $(this).html('Světlé pozadí');      
    } else {
      $('#full-photo-canvas').css('background','#f8f7f5 url("/media/img/container.gif") repeat left top');
      $(this).html('Tmavé pozadí');
    }
  });
  
  $(window).resize(function() {
    //alert('a');
    var img_max_width = 0;
    var img_max_height = 0;
    var window_width = $(window).width();
    var window_height = $(window).height();
    var i = 0;
    //alert(window_height);

    $("#full-photo-images img").each(function() {
      if ($(this).height() > window_height) {
        var h = window_height;
        var w = Math.ceil($(this).width() / $(this).height() * window_height);
      }
      $(this).css({height: (h-100), width: (w-100)});
    });

    $("#full-photo-images img").each(function(){
      i++;
      var img_height_new = $(this).height();
      if(img_max_height < img_height_new) {
        img_max_height = img_height_new;
      }
      var img_width_new = $(this).width();
      if(img_max_width < img_width_new) {
        img_max_width = img_width_new;
      }
    });
    $('#full-photo-images').css({
      'width': img_max_width,
      'height': img_max_height
    });
    $('#full-photo-images ul').css({
      'width': (img_max_width+45)*i
    });
    $('#full-photo-content').css({
      'left': (window_width - $('#full-photo-content').outerWidth())/2,
      'top': (window_height - $('#full-photo-content').outerHeight())/2
    });

  });  

});

var keyboardArrow = function(event) {
  var sizeImg = $('#full-photo-images li').size();
  if(sizeImg == 1) {
    return null;
  } else {
    if (event.keyCode == '39') {
      righSlide();
    }
    if (event.keyCode == '37') {
      leftSlide();
    }
  }
}

function righSlide() {  
  var rightslide = $('#full-photo-images li.active').next().width()+40;
  var newVisible = $('#full-photo-images li.active').next();
  //alert(newVisible.length);
  if (newVisible.length > 0) {
    $(document).unbind('keydown');
    $('#full-photo-images li.active').removeClass('active').css("opacity",0.3);
    $(newVisible).addClass('active').animate({opacity: 1});
    $('#full-photo-images ul').animate({
      left: '-='+rightslide+"px"
    },500,function(){
      $(document).bind('keydown',keyboardArrow);
    });
  } else {return;}
}

function leftSlide() {
  var leftslide = $('#full-photo-images li.active').prev().width()+40;
  var newVisible = $('#full-photo-images li.active').prev();
  //alert(newVisible.length);
  if (newVisible.length > 0) {
    $(document).unbind('keydown');
    $('#full-photo-images li.active').removeClass('active').css("opacity",0.3);
    $(newVisible).addClass('active').animate({opacity: 1});
    $('#full-photo-images ul').animate({
      left: '+='+leftslide+"px"
    },500,function(){
      $(document).bind('keydown',keyboardArrow);
    });
  }
}